var http = require("http");
var fs = require("fs");
var zlib = require("zlib");
var events = require("events");
var eventEmitter = new events.EventEmitter();
var data = "";

//Stream 流
//仅读流
var readData = fs.createReadStream("index.html");
readData.setEncoding("utf-8");
readData.on("data",function(chunk){
	console.log(chunk);
	data += chunk;
})

readData.on("end",function(){
	console.log(data);
})
//仅写流
// var writeStream = fs.createWriteStream("index.html");
// writeStream.write("22222","utf-8");
// writeStream.end();
// writeStream.on("finish",function(){
// 	console.log("写入数据成功！");
// })

//可读可写流 --- 不明白
// var douplex = fs.douplex("index.html");
// douplex.on("data",function(chunk){
// 	console.log(chunk);
// })

//通过pipe传递数据流
// var readSteam = fs.createReadStream("new_file.html");
// var writeStream2  = fs.createWriteStream("index.html");
// readSteam.pipe(writeStream2);
// //查出写入数据
// setTimeout(()=>{
// 	var readStream3  = fs.createReadStream("index.html");
// 	readStream3.setEncoding("utf-8");
// 	readStream3.on("data",function(chunk){
// 		console.log(chunk);
// 	})
// },1000)

//通过zlib压缩pipe的数据流 --- index.text.gz文件损坏
// var readSteam = fs.createReadStream("new_file.html");
// var writeStream2  = fs.createWriteStream("index.txt");
// readSteam.pipe(zlib.createGzip());
// readSteam.pipe(writeStream2);
//查出写入数据
// setTimeout(()=>{
// 	var readStream3  = fs.createReadStream("index.html");
// 	readStream3.setEncoding("utf-8");
// 	readStream3.on("data",function(chunk){
// 		console.log(chunk);
// 	})
// },1000)

//通过zlib读取压缩pipe的数据流 ---
//var readSteam2 = fs.createReadStream("lodash.js");
//var writeStream22  = fs.createWriteStream("index.txt");
//readSteam2.pipe(writeStream22)
////查出写入数据
//setTimeout(()=>{
//	var readStream3  = fs.createReadStream("index.txt");
//	readStream3.setEncoding("utf-8");
//	readStream3.on("data",function(chunk){
//		console.log(chunk);
//	})
//},3000)

//Buffer 二进制流
// var buf = Buffer.from("a","ascii");
var buf = Buffer.alloc(10);
var wVal = buf.write("wjy");
// console.log(wVal);
// console.log(buf.toString("ascii",0.5));
// console.log(buf.toString("hex"));

http.createServer(function(res,rsp){
//	rsp.writeHead(200,{"Content-Type":"plain-text"});	
//	rsp.end("Hello World1231231");
	
}).listen(8888);
			
//阻塞代码
//var fsData = fs.readFileSync('index.html');
//console.log(fsData.toString());

//非阻塞代码
fs.readFile('index.html',(err,data)=>{
//	console.log(err);
	console.log(data.toString());
})
console.log("server running 127.0.0.1:8888");		

eventEmitter.on("some_event",(res)=>{
//	console.log("事件触发！");
})
setTimeout(()=>{
	eventEmitter.emit("some_event");
	// eventEmitter.emit("error");
},2000)


